package cn.sylinx.horm.dialect.sql;

import java.util.regex.Pattern;

import cn.sylinx.horm.util.GLog;
import cn.sylinx.horm.util.Tuple;

class SqlServerSqlBuilder extends DefaultSqlBuilder {

    @Override
    protected String[] getEscapeChar() {
        return new String[] { "[", "]" };
    }

    @Override
    public Tuple buildPaginatorSql(String preSql, int pageNumber, int pageSize) {

        String reg = "[oO][rR][dD][eE][rR]( )+[bB][yY]";
        Pattern p = Pattern.compile(reg);
        String[] split = p.split(preSql);
        String orderBy = null;
        if (split.length > 1) {
            preSql = split[0];
            orderBy = "order by" + split[1];
        } else {
            orderBy = "order by id desc";
        }

        String sqlCount = "select count(1) as totalCount from (" + preSql + ") as temp";
        int offset = pageSize * (pageNumber - 1);
        StringBuilder psql = new StringBuilder();
        psql.append("select top ").append(pageSize).append(" o.* from (");
        psql.append(" select row_number() over(").append(orderBy).append(") as rownumber,* from (");
        psql.append(preSql).append(") as oo) as o where rownumber > ").append(offset);
        String pageSql = psql.toString();
        GLog.debug("sqlserver page sql: {}", pageSql);

        Object[] params = new Object[] {};
        return Tuple.apply(sqlCount, pageSql, params);
    }

}
